package com.xiaohudie.util;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @Author xiao hu die
 * @Date 2022/3/8 14:31
 * @Version 1.0
 */
public class SimpleLock implements ILock{
    private String name;
    private StringRedisTemplate stringRedisTemplate;
    private final String LocalSign = UUID.randomUUID().toString(true);
    /**解析lua脚本*/
    private static DefaultRedisScript<Integer> unlock_script = null;
    static {
        unlock_script =new DefaultRedisScript<>();
        unlock_script.setLocation(new ClassPathResource("unlock.lua"));
        unlock_script.setResultType(Integer.class);
    }

    public SimpleLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }
    @Override
    public boolean tryLock(long timeoutSec) {
        /**线程的标识应该使用uuid来确保唯怡*/
        /**尝试获取锁*/
        Boolean isTrue = stringRedisTemplate.opsForValue().setIfAbsent(name,LocalSign+ String.valueOf(Thread.currentThread().getId()), timeoutSec, TimeUnit.SECONDS);
        /**消除自动拆箱的空指针风险*/
        return Boolean.TRUE.equals(isTrue);
    }
    /**使用lua脚本实现删除锁的操作
     * 目的是保证删除锁的操作是原子性的*/
    @Override
    public void unlock() {
        stringRedisTemplate.execute(
                unlock_script,
                Collections.singletonList(name),
                LocalSign+Thread.currentThread().getId()
        );
    }

 /*   @Override
    public void unlock() {
        *//**获取当前线程的唯怡标识*//*
        String Sing = LocalSign +Thread.currentThread().getId();
        *//**获取redis中的线程标识*//*
        String s = stringRedisTemplate.opsForValue().get(name);
        if (Sing.equals(s)) {
            *//**释放锁*//*
            Boolean delete = stringRedisTemplate.delete(name);
        }
    }*/
}
